package com.jxbeidou.gateway.util;

import com.jxbeidou.core.constents.SecurityConstants;
import com.jxbeidou.core.entity.R;
import com.jxbeidou.core.exception.ErrorCode;
import com.jxbeidou.core.util.JsonUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.Charset;

/**
 * @program: jxbeidou-cloud-gateway
 * @ClassName: ReactiveHttpUtil
 * @description: Http工具类
 * @author: 杜晓祥
 * @create: 2023-12-19 09:20
 * 版权所有：交信北斗(北京)信息科技有些公司
 */
public class ReactiveHttpUtil {

    public static Mono responseText (ServerHttpResponse response, String message) {
        response.setStatusCode(HttpStatus.OK);
        response.getHeaders().set(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
        response.getHeaders().set("Access-Control-Allow-Origin","*");
        response.getHeaders().set("Cache-Control","no-cache");
        DataBuffer buffer =  response.bufferFactory().wrap(message.getBytes(Charset.defaultCharset()));
        return response.writeWith(Mono.just(buffer));
    }

    public static Mono responseResult (ServerHttpResponse response, String message) {
        R<String> result = R.validateFailed(message);
        String json = JsonUtil.toJsonString(result);
        return responseText(response, json);
    }

    public static Mono responseJson (ServerHttpResponse response, ErrorCode errorCode) {
        R<String> result = R.failed(errorCode);
        String json = JsonUtil.toJsonString(result);
        return responseText(response, json);
    }

    public static void clearHeaderToken (ServerWebExchange exchange) {
        ServerHttpRequest request = exchange
                .getRequest()
                .mutate()
                .header(SecurityConstants.AUTHENTICATION, "")
                .build();
        exchange = exchange.mutate().request(request).build();
    }

    public static String getToken(ServerHttpRequest request)
    {
        String token = request.getHeaders().getFirst(SecurityConstants.AUTHENTICATION);
        if (StringUtils.isEmpty(token)) {
            return null;
        }
        if (token.startsWith(SecurityConstants.PREFIX)) {
            token = token.replaceFirst(SecurityConstants.PREFIX, StringUtils.EMPTY);
        }
        return token;
    }

}
